package com.example.hy_homework5;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    public static int MODE = MODE_PRIVATE;
    public static final String PREFERENCE_NAME = "SaveSetting";
    public static final String KEY_ACCOUNT = "account";
    public static final String KEY_PASSWORD = "password";

    Button btnLogin;
    EditText etAccount, etPassword;
    SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnLogin = findViewById(R.id.btn_login);
        etAccount = findViewById(R.id.account_input);
        etPassword = findViewById(R.id.password_input);

        btnLogin.setOnClickListener(this);

        sharedPreferences = getSharedPreferences(PREFERENCE_NAME, MODE);

        String savedAccount = sharedPreferences.getString(KEY_ACCOUNT, "");
        String savedPassword = sharedPreferences.getString(KEY_PASSWORD, "");

        if (!savedAccount.isEmpty() && !savedPassword.isEmpty()) {
            etAccount.setText(savedAccount);
            etPassword.setText(savedPassword);
        }
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_login) {
            String account = etAccount.getText().toString().trim();
            String password = etPassword.getText().toString().trim();

            if (account.isEmpty() || password.isEmpty()) {
                Toast.makeText(this, "账号或密码不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString(KEY_ACCOUNT, account);
            editor.putString(KEY_PASSWORD, password);
            editor.apply();

            Toast.makeText(this, "登录成功，账号密码已保存", Toast.LENGTH_SHORT).show();
        }
    }
}